// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database({
	throwOnNotFound: false
})
const _ = db.command
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext()
	let staff = await db.collection('staff').field({
		group_id: true,
		rule_appoints: true
	}).where({
		_openid: wxContext.OPENID,
		shop_id: event.shop_id,
	}).get()
	if (staff.data.length == 0) {
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	staff = staff.data[0]

	if (staff.group_id == 3 || (staff.group_id == 2 && !staff.rule_appoints)) {
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	let match = {
		shop_id: event.shop_id
	}
	if(event.status>0){
		match.status = parseInt(event.status)
	}
	if(event.date){
		let date = new Date(event.date)
		date.setMinutes(date.getMinutes()-480-date.getTimezoneOffset())
		match.appoint_date = date.getTime()
		console.log(date.getTime())
	}
	if(event.search){
		match = _.and([
			match,
			_.or([{
				name: db.RegExp({
					regexp: event.search,
					options: 'i',
				})
			}, {
				idcard: db.RegExp({
					regexp: event.search,
					options: 'i',
				})
			}, {
				phone: db.RegExp({
					regexp: event.search,
					options: 'i',
				})
			}])
		])
		
	}
	const $ = db.command.aggregate
	let list = await db.collection('appoint').aggregate().lookup({
		from: 'product',
		localField: 'product_id',
		foreignField: '_id',
		as: 'product'
	}).lookup({
		from: 'timeline',
		localField: 'timeline_id',
		foreignField: '_id',
		as: 'timeline'
	}).lookup({
		from: 'daily',
		localField: 'daily_id',
		foreignField: '_id',
		as: 'daily'
	}).match(match).skip(event.skip).limit(15).project({
		_id:true,
		name:true,
		type:true,
		status:true,
		product:$.arrayElemAt(['$product',0]),
		timeline:$.arrayElemAt(['$timeline',0]),
		daily:$.arrayElemAt(['$daily',0]),
	}).end()
	return {
		code: 200,
		data: list.list
	}
}